<template>
  <div class="profile-page">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h3>个人中心</h3>
        </div>
      </template>

      <el-tabs v-model="activeTab" class="profile-tabs">
        <!-- 个人信息 -->
        <el-tab-pane label="个人信息" name="info">
          <div class="tab-header">
            <el-button
              v-if="!isEditing"
              type="primary"
              @click="handleEdit"
            >
              编辑资料
            </el-button>
            <div v-else>
              <el-button @click="handleCancel">取消</el-button>
              <el-button
                type="primary"
                :loading="saveLoading"
                @click="handleSave"
              >
                保存
              </el-button>
            </div>
          </div>

          <div v-loading="loading" class="profile-content">
        <!-- 查看模式 -->
        <div v-if="!isEditing" class="view-mode">
          <!-- 头像 -->
          <div class="profile-item avatar-section">
            <el-avatar :size="120" :src="userInfo.avatar">
              <el-icon :size="60"><User /></el-icon>
            </el-avatar>
          </div>

          <!-- 用户信息 -->
          <div class="info-section">
            <div class="info-item">
              <label>用户名：</label>
              <span>{{ userInfo.username }}</span>
            </div>

            <div class="info-item">
              <label>邮箱：</label>
              <span>{{ userInfo.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>手机号：</label>
              <span>{{ userInfo.phone || '未设置' }}</span>
            </div>
          </div>
        </div>

        <!-- 编辑模式 -->
        <div v-else class="edit-mode">
          <el-form
            ref="formRef"
            :model="editForm"
            :rules="formRules"
            label-width="100px"
          >
            <!-- 头像 -->
            <el-form-item label="头像">
              <div class="avatar-upload">
                <el-avatar :size="100" :src="editForm.avatar">
                  <el-icon :size="50"><User /></el-icon>
                </el-avatar>
                <el-upload
                  action="/api/user/upload/avatar"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  accept="image/*"
                >
                  <el-button type="primary" size="small" style="margin-top: 10px">
                    更换头像
                  </el-button>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 用户名（不可编辑） -->
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled />
            </el-form-item>

            <!-- 邮箱 -->
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="editForm.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="editForm.phone"
                placeholder="请输入手机号"
                maxlength="11"
              />
            </el-form-item>
          </el-form>
        </div>
          </div>
        </el-tab-pane>

        <!-- 我报名的活动 -->
        <el-tab-pane label="我的报名" name="enrollments">
          <div v-loading="enrollmentsLoading" class="enrollments-container">
            <el-empty v-if="!enrollmentsLoading && enrollments.length === 0" description="暂无报名记录" />
            
            <div v-else class="activity-list">
              <el-card
                v-for="enrollment in enrollments"
                :key="enrollment.enrollmentId"
                class="activity-card"
                shadow="hover"
              >
                <div class="activity-content">
                  <div class="activity-image">
                    <el-image
                      :src="enrollment.activityImages[0] || '/default-activity.jpg'"
                      fit="cover"
                      style="width: 100%; height: 100%"
                    />
                  </div>
                  <div class="activity-info">
                    <h3 class="activity-title">{{ enrollment.activityTitle }}</h3>
                    <p class="activity-desc">{{ enrollment.activityDescription }}</p>
                    <div class="activity-meta">
                      <div class="meta-item">
                        <el-icon><Calendar /></el-icon>
                        <span>{{ formatTime(enrollment.activityStartTime) }} - {{ formatTime(enrollment.activityEndTime) }}</span>
                      </div>
                      <div class="meta-item">
                        <el-icon><Location /></el-icon>
                        <span>{{ enrollment.activityLocation }}</span>
                      </div>
                      <div class="meta-item">
                        <el-icon><Clock /></el-icon>
                        <span>报名时间：{{ formatTime(enrollment.enrollTime) }}</span>
                      </div>
                    </div>
                    <div class="status-row">
                      <el-tag :type="getActivityStatusType(enrollment.activityStatus)">
                        {{ getActivityStatusText(enrollment.activityStatus) }}
                      </el-tag>
                      <el-tag :type="getEnrollStatusType(enrollment.enrollStatus)" style="margin-left: 10px">
                        {{ getEnrollStatusText(enrollment.enrollStatus) }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>

        <!-- 我申领的失物 -->
        <el-tab-pane label="我的申领" name="claims">
          <div v-loading="claimsLoading" class="claims-container">
            <el-empty v-if="!claimsLoading && claims.length === 0" description="暂无申领记录" />
            
            <div v-else class="claim-list">
              <el-card
                v-for="claim in claims"
                :key="claim.claimId"
                class="claim-card"
                shadow="hover"
              >
                <div class="claim-content">
                  <div class="claim-image">
                    <el-image
                      :src="claim.itemImages[0] || '/default-lost-item.jpg'"
                      fit="cover"
                      style="width: 100%; height: 100%"
                    />
                  </div>
                  <div class="claim-info">
                    <h3 class="claim-title">{{ claim.itemTitle }}</h3>
                    <div class="claim-meta">
                      <div class="meta-item">
                        <el-icon><Folder /></el-icon>
                        <span>{{ claim.itemCategory }}</span>
                      </div>
                      <div class="meta-item">
                        <el-icon><Location /></el-icon>
                        <span>{{ claim.itemLocation }}</span>
                      </div>
                      <div class="meta-item">
                        <el-icon><Clock /></el-icon>
                        <span>拾取时间：{{ formatTime(claim.itemFoundTime) }}</span>
                      </div>
                      <div class="meta-item">
                        <el-icon><Clock /></el-icon>
                        <span>申领时间：{{ formatTime(claim.claimTime) }}</span>
                      </div>
                    </div>
                    <div class="claim-reason">
                      <strong>申领理由：</strong>{{ claim.reason }}
                    </div>
                    <div v-if="claim.claimStatus === 2 && claim.auditReason" class="audit-reason">
                      <strong>驳回原因：</strong><span class="reason-text">{{ claim.auditReason }}</span>
                    </div>
                    <div class="status-row">
                      <el-tag :type="getItemStatusType(claim.itemStatus)">
                        {{ getItemStatusText(claim.itemStatus) }}
                      </el-tag>
                      <el-tag :type="getClaimStatusType(claim.claimStatus)" style="margin-left: 10px">
                        {{ getClaimStatusText(claim.claimStatus) }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Calendar, Clock, Location, Folder } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { reqUserDetail, reqUpdateUserInfo, reqUserEnrollments, reqUserClaims } from '@/api/user'
import type { UserDetailInfo, UserEnrollment, UserClaim } from '@/api/user/type'
import useUserStore from '@/stores/modules/user'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 标签页
const activeTab = ref('info')

// 状态
const loading = ref(false)
const saveLoading = ref(false)
const isEditing = ref(false)
const formRef = ref<FormInstance>()

// 报名和申领数据
const enrollments = ref<UserEnrollment[]>([])
const claims = ref<UserClaim[]>([])
const enrollmentsLoading = ref(false)
const claimsLoading = ref(false)

// 用户信息
const userInfo = ref<UserDetailInfo>({
  username: '',
  avatar: '',
  nickname: '',
  email: '',
  phone: ''
})

// 编辑表单
const editForm = reactive<UserDetailInfo>({
  username: '',
  avatar: '',
  nickname: '',
  email: '',
  phone: ''
})

// 上传请求头
const uploadHeaders = computed(() => ({
  token: userStore.token || ''
}))

// 表单验证规则
const formRules = reactive<FormRules>({
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
})

// 获取用户详细信息
const getUserDetail = async () => {
  loading.value = true

  try {
    const result: any = await reqUserDetail()
    if (result.code === 200) {
      userInfo.value = result.data
    } else {
      ElMessage.error(result.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 进入编辑模式
const handleEdit = () => {
  isEditing.value = true
  // 复制用户信息到编辑表单
  Object.assign(editForm, userInfo.value)
}

// 取消编辑
const handleCancel = () => {
  isEditing.value = false
  // 重置表单
  formRef.value?.resetFields()
}

// 保存修改
const handleSave = async () => {
  if (!formRef.value) return

  // 验证表单
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请检查表单填写是否正确')
      return
    }

    saveLoading.value = true

    try {
      const updateData = {
        avatar: editForm.avatar,
        nickname: editForm.nickname,
        email: editForm.email,
        phone: editForm.phone
      }

      const result: any = await reqUpdateUserInfo(updateData)

      if (result.code === 200) {
        ElMessage.success('保存成功')

        // 更新用户信息
        Object.assign(userInfo.value, editForm)

        // 更新store中的头像
        if (editForm.avatar !== userStore.avatar) {
          userStore.avatar = editForm.avatar
        }

        isEditing.value = false
      } else {
        ElMessage.error(result.message || '保存失败')
      }
    } catch (error: any) {
      console.error('保存失败:', error)
      ElMessage.error(error.message || '保存失败')
    } finally {
      saveLoading.value = false
    }
  })
}

// 头像上传前验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

// 头像上传成功
const handleAvatarSuccess = (response: any) => {
  if (response.code === 200) {
    editForm.avatar = response.data.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 获取用户报名的活动
const getUserEnrollments = async () => {
  enrollmentsLoading.value = true
  try {
    const result: any = await reqUserEnrollments()
    if (result.code === 200) {
      enrollments.value = result.data
    } else {
      ElMessage.error(result.message || '获取报名记录失败')
    }
  } catch (error) {
    console.error('获取报名记录失败:', error)
    ElMessage.error('获取报名记录失败')
  } finally {
    enrollmentsLoading.value = false
  }
}

// 获取用户申领的失物
const getUserClaims = async () => {
  claimsLoading.value = true
  try {
    const result: any = await reqUserClaims()
    if (result.code === 200) {
      claims.value = result.data
    } else {
      ElMessage.error(result.message || '获取申领记录失败')
    }
  } catch (error) {
    console.error('获取申领记录失败:', error)
    ElMessage.error('获取申领记录失败')
  } finally {
    claimsLoading.value = false
  }
}

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 活动状态相关
const getActivityStatusType = (status: number) => {
  const types: Record<number, any> = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return types[status] || ''
}

const getActivityStatusText = (status: number) => {
  const texts: Record<number, string> = {
    0: '未开始',
    1: '进行中',
    2: '已结束'
  }
  return texts[status] || '未知'
}

// 报名状态相关
const getEnrollStatusType = (status: number) => {
  const types: Record<number, any> = {
    0: 'success',
    1: 'info'
  }
  return types[status] || ''
}

const getEnrollStatusText = (status: number) => {
  const texts: Record<number, string> = {
    0: '已报名',
    1: '已取消'
  }
  return texts[status] || '未知'
}

// 失物状态相关
const getItemStatusType = (status: number) => {
  const types: Record<number, any> = {
    0: 'success',
    1: 'warning',
    2: 'info'
  }
  return types[status] || ''
}

const getItemStatusText = (status: number) => {
  const texts: Record<number, string> = {
    0: '待认领',
    1: '已申领',
    2: '已归还'
  }
  return texts[status] || '未知'
}

// 申领状态相关
const getClaimStatusType = (status: number) => {
  const types: Record<number, any> = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return types[status] || ''
}

const getClaimStatusText = (status: number) => {
  const texts: Record<number, string> = {
    0: '待审核',
    1: '已通过',
    2: '已驳回'
  }
  return texts[status] || '未知'
}

// 监听标签页切换
watch(activeTab, (newTab) => {
  if (newTab === 'enrollments' && enrollments.value.length === 0) {
    getUserEnrollments()
  } else if (newTab === 'claims' && claims.value.length === 0) {
    getUserClaims()
  }
})

// 页面加载时获取用户信息
onMounted(() => {
  getUserDetail()
})
</script>

<style scoped lang="scss">
.profile-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }
}

.profile-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 20px;
  }
}

.tab-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.profile-content {
  min-height: 400px;
}

.view-mode {
  .avatar-section {
    display: flex;
    justify-content: center;
    margin-bottom: 40px;
    padding: 20px;
  }

  .info-section {
    max-width: 500px;
    margin: 0 auto;

    .info-item {
      display: flex;
      padding: 15px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      label {
        min-width: 100px;
        font-weight: 600;
        color: #606266;
      }

      span {
        flex: 1;
        color: #303133;
      }
    }
  }
}

.edit-mode {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px 0;

  .avatar-upload {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}

// 报名活动列表
.enrollments-container,
.claims-container {
  min-height: 300px;
}

.activity-list,
.claim-list {
  display: grid;
  gap: 20px;
}

.activity-card,
.claim-card {
  .activity-content,
  .claim-content {
    display: flex;
    gap: 20px;
  }

  .activity-image,
  .claim-image {
    width: 200px;
    height: 150px;
    flex-shrink: 0;
    border-radius: 8px;
    overflow: hidden;
    background: #f5f7fa;
  }

  .activity-info,
  .claim-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .activity-title,
  .claim-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .activity-desc {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .activity-meta,
  .claim-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .meta-item {
      display: flex;
      align-items: center;
      gap: 6px;
      color: #909399;
      font-size: 14px;

      .el-icon {
        font-size: 16px;
      }
    }
  }

  .claim-reason,
  .audit-reason {
    font-size: 14px;
    color: #606266;
    line-height: 1.5;

    strong {
      color: #303133;
    }
  }

  .audit-reason {
    padding: 10px;
    background: #fef0f0;
    border-radius: 4px;
    border-left: 3px solid #f56c6c;

    .reason-text {
      color: #f56c6c;
    }
  }

  .status-row {
    display: flex;
    align-items: center;
    margin-top: auto;
  }
}

@media (max-width: 768px) {
  .profile-page {
    padding: 10px;
  }

  .view-mode .info-section .info-item {
    flex-direction: column;

    label {
      margin-bottom: 5px;
    }
  }

  .activity-content,
  .claim-content {
    flex-direction: column !important;
  }

  .activity-image,
  .claim-image {
    width: 100% !important;
    height: 200px !important;
  }
}
</style>
